package demo09;

import java.util.Stack;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 1. 已知数字1, 2, 3, 4,  将它们组合成4位数, 并且存储到合适的集合中, 然后按照3个一行的格式, 降序输出.
 * 2. 要求1: 该4位数必须同时包含1, 2, 3, 4这四个数字.	//例如: 1234, 1423都可以,  1122不行.
 * 3. 要求2: 该4位数不能以3开头.  						//例如: 1234可以,  3214不行.
 * 4. 要求3: 该4位数中, 数字1和3不能挨着.  			//例如: 1234可以, 1324, 2314不行.
 * 5. 输出格式如下:
 * 4321	4312	4123
 * 3421	...
 */
public class Test {
    public static Stack<Integer> stack = new Stack<>();
    public static TreeSet<Integer> ts = new TreeSet<Integer>((e1, e2) -> e2 - e1);

    public static void main(String[] args) {
        int[] num = new int[]{1, 2, 3, 4};
        trace(num, 4, 0);
        AtomicInteger count = new AtomicInteger();
        ts.forEach(e -> System.out.print(e + (count.incrementAndGet() % 3 == 0 ? "\r\n" : "\t")));
    }

    public static void trace(int[] num, int mark, int currentMark) {
        if (mark == currentMark) {
            if (stack.get(0) == 3)
                return;
            for (int i = 0; i < stack.size() - 1; i++) {            //该4位数中, 数字1和3不能挨着
                if ((stack.get(i) == 1 && stack.get(i + 1) == 3) || (stack.get(i) == 3 && stack.get(i + 1) == 1))
                    return;
            }
            int temp = 0;
            for (int i = 0; i < stack.size(); i++) {
                temp = temp * 10 + stack.get(i);
            }
            ts.add(temp);
            return;
        }
        for (int i = 0; i < num.length; i++) {
            if (!stack.contains(num[i])) {
                stack.add(num[i]);
                trace(num, mark, currentMark + 1);
                stack.pop();
            }
        }
    }
}
